package chances.epg.navigator.history;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import chances.epg.commons.utils.PathUtils;
import chances.epg.navigator.context.AccessContext;
import chances.epg.navigator.context.AccessContextUtils;
import chances.epg.session.UserSession;

@Component
public class NavigateHistoryFactory {

	public static NavigateHistory createHistory(HttpServletRequest request, String defaultEntry) {
		String entry = defaultEntry;

		String returnURL = request.getParameter("returnURL");
		if (StringUtils.isBlank(returnURL)) {
			returnURL = request.getParameter("backUrl");
		}

		if (StringUtils.isNotBlank(returnURL)) {
			entry = returnURL;
		}

		NavigateHistory history = new NavigateHistory(entry);
		return history;
	}

	public static HistoryEntry createHistoryEntry(HttpServletRequest request) {
		HistoryEntry entry = new HistoryEntry();
		entry.setPath(PathUtils.join(request.getServletContext().getContextPath(), request.getServletPath()));
		entry.setQueryString(request.getQueryString());
		return entry;
	}

	/**
	 * 
	 * @param httpRequest
	 * @return
	 */
	public static NavigateHistory getHistory(HttpServletRequest httpRequest, UserSession userSession) {
		NavigateHistory history = (NavigateHistory) userSession.getAttribute(NavigateHistory.ACCESS_HISTORY_NAME);
		if (history == null) {
			AccessContext context = AccessContextUtils.getAccessContext(httpRequest);
			if (context != null) {
				history = createHistory(httpRequest, context.getEpgSiteContext().getHome());
			} else {
				history = createHistory(httpRequest, userSession.getLoginUrl());
			}

			userSession.setAttribute(NavigateHistory.ACCESS_HISTORY_NAME, history);
		}
		return history;
	}

	public static void removeHistory(UserSession userSession) {

		if (userSession != null) {
			userSession.removeAttribute(NavigateHistory.ACCESS_HISTORY_NAME);
		}
	}

}
